<template>
  <div>
    <div class="tool-bar">
      <button @click="play(1)">坐下</button>
      <button @click="play(2)">握手</button>
      <button @click="play(3)">打滚</button>
      <button @click="play(4)">躺下</button>
    </div>
    <div id="container"></div>
  </div>
</template>

<script setup>
import * as THREE from "three";
import { onMounted, ref } from "vue";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { VertexNormalsHelper } from "three/addons/helpers/VertexNormalsHelper.js";
let mixer, dogModel, animations;
const clock = new THREE.Clock();
const scene = new THREE.Scene();
const renderer = new THREE.WebGLRenderer({ antialias: true });
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
onMounted(() => {
  init();
  animate();
});
function play(v) {
  if (mixer) {
    mixer = new THREE.AnimationMixer(dogModel);
    mixer.clipAction(animations[v]).play()
  }
}
function init() {
  camera.position.set(200, 100, 200);

  scene.background = new THREE.Color(0xa0a0a0);
  scene.fog = new THREE.Fog(0xa0a0a0, 200, 1000);

  const hemiLight = new THREE.HemisphereLight(0xffffff, 0x444444);
  hemiLight.position.set(0, 200, 0);
  scene.add(hemiLight);

  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.shadowMap.enabled = true;
  document.getElementById("container").appendChild(renderer.domElement);

  const controls = new OrbitControls(camera, renderer.domElement);
  controls.maxPolarAngle = Math.PI / 2;
  controls.update();

  window.addEventListener('resize', onWindowResize);

  const loader = new GLTFLoader();
  loader.load("gltf/play-ful-dog.glb", function (gltf) {
    dogModel = gltf.scene.children[0];
    dogModel.scale.x = 1
    dogModel.scale.y = 1
    dogModel.scale.z = 1
    scene.add(dogModel);
    animations = gltf.animations
    mixer = new THREE.AnimationMixer(dogModel);
    mixer.clipAction(animations[0]).play()
  });
}

function onWindowResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
  if (mixer) {
    mixer.update(clock.getDelta())
  }
}

</script>

<style>
.tool-bar {
  position: fixed;
  left: 50%;
  bottom: 10%;
  transform: translateX(-50%);
}
.tool-bar button {
  width: 60px;
  margin: 10px;
  line-height: 26px;
  text-align: center;
  cursor: pointer;
}
</style>